package vn.conghuy.talkwithme.data.livescore;

import java.io.IOException;
import java.util.ArrayList;

import org.jsoup.Jsoup;

public class LivescoreParser {
	
	public static final int LT_PREMIER_LEAGUE = 0;
	public static final int LT_LALIGA = 1;
	public static final int LT_SERIA = 2;
	
	private static final String LEAGUE_NAME_START = "<td class=\"title\" colspan=\"4\" height=\"18\">&nbsp;<b>";
	private static final String MATCH_TIME_START = "<td width=\"45\" height=\"18\">&nbsp";
	private static final String MATCH_HOME_START = "<td align=\"right\" width=\"186\">";
	private static final String MATCH_SCORE_START = "<td align=\"center\" width=\"51\">";
	private static final String  MATCH_AWAY_START = "<td width=\"186\">";
	
	
	ArrayList<LivescoreLeague> leagues;
	int leagueType;
	
	String contentHtml;
	
	public LivescoreParser() {
		super();
		leagues = new ArrayList<LivescoreLeague>();
	}
	
	@SuppressWarnings("null")
	public boolean update(){
		leagues.clear();
		String html = "";
		try {
			html = Jsoup.connect("http://livescore.com").userAgent("Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1").get().html();
			contentHtml = html;
		
		
			String[] lines = html.split("\n");
			LivescoreLeague currentLeague = null;
			LivescoreMatch currentMatch = null;
			for(String line : lines){
				line = line.trim();
				if(line.startsWith(LEAGUE_NAME_START)){
					LivescoreLeague newLeague = new LivescoreLeague();
					String name = line.substring(line.indexOf("<b>"));
					name = name.replaceAll("<b>|</b>|</td>", "");
					newLeague.name = Jsoup.parse(name).text();;
					leagues.add(newLeague);
					currentLeague = newLeague;
				}
				else if(line.startsWith(MATCH_TIME_START)){
					LivescoreMatch newMatch = new LivescoreMatch();
					String time = line.substring(line.indexOf("&nbsp;"));
					time = time.replaceAll("&nbsp;|</td>", "");
					if(time.contains("<img")){		//match is playing
						time = time.substring(time.indexOf(">")+1);
					}
					newMatch.startTime = time;
					currentLeague.addMatch(newMatch);
					currentMatch = newMatch;
				}
				else if(line.startsWith(MATCH_HOME_START)){
					String name = line.substring(line.indexOf(">"));
					name = name.replaceAll(">|</td>", "");
					currentMatch.home = Jsoup.parse(name).text();;
				}
				else if(line.startsWith(MATCH_SCORE_START)){
					String score;
					int linkIndex = line.indexOf("href=");
					if(linkIndex > 0){
						score = line.substring(linkIndex);
						score = score.substring(score.indexOf("\">"));
						score = score.replaceAll("\">|</a></td>", "");
					}
					else {
						score = line.substring(line.indexOf(">"));
						score = score.replaceAll(">|</td>", "");
					}
					
					
					// get score and get link
					String[] scoreElem = score.split(" - ");
					try{
						currentMatch.homeScore = Integer.valueOf(scoreElem[0]);
						currentMatch.awayScore = Integer.valueOf(scoreElem[1]);
					}
					catch(Exception e){}
					
					//get link
					
					if(linkIndex >0){
						String linkStr = line.substring(linkIndex);
						linkStr = linkStr.substring(linkStr.indexOf("/"), linkStr.indexOf("\">"));
						linkStr = Jsoup.parse(linkStr).text();
						linkStr = "http://livescore.com"+linkStr;
						currentMatch.link = linkStr;
					}
				}
				else if(line.startsWith(MATCH_AWAY_START)){
					String name = line.substring(line.indexOf(">"));
					name = name.replaceAll(">|</td>", "");
					currentMatch.away = Jsoup.parse(name).text();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	public String leagueLiveScore(String keyword){
		
		//LEAGUE
		ArrayList<LivescoreLeague> chooseLeagues = LivescoreLeague.elementInArrayIsWordOfStr(leagues, keyword);
		
		StringBuilder strBuilder = new StringBuilder();
		if(chooseLeagues.size() > 0){
			//build string.
			for(LivescoreLeague chooseLeague: chooseLeagues){
				strBuilder.append(chooseLeague.name).append(" : \n");
				for(LivescoreMatch match : chooseLeague.matches){
					
					strBuilder.append(match.toString()).append("\n");
				}
				strBuilder.append("\n");
			}
		}
		
		//MATCH
		ArrayList<LivescoreMatch> chooseMatchs = LivescoreLeague.matchsInLeagueArrayHasTeamMatchKeyword(leagues, keyword);
		if(chooseMatchs.size() > 0){
			if(chooseLeagues.size() > 0) strBuilder.append("\n -------\n");
			strBuilder.append("Match detail:\n\n");
		
			for(LivescoreMatch chooseMatch: chooseMatchs){
				chooseMatch.updateEvent();
				strBuilder.append(chooseMatch.toStringDetail()).append("\n --- \n");
			}
		}
		if(chooseLeagues.size() == 0 && chooseMatchs.size() == 0) return null;
		return strBuilder.toString();
	}

}
